from fastapi import APIRouter, HTTPException, Query
from typing import Optional, List
from app.models.schemas import (
    FeedBookRequest, 
    FeedBookResponse,
    DeleteBookRequest,
    GetElfBooksResponse,
    Book,
    ErrorResponse
)
from app.services.book_service import BookService
import logging

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/books", tags=["书籍管理"])

@router.post("/feed", response_model=FeedBookResponse)
async def feed_book_to_elf(request: FeedBookRequest):
    """
    精灵阅读书籍接口
    - 更新书籍的elf_list
    - 提升精灵智力属性（+50）
    - 同步更新精灵档案
    """
    try:
        result = await BookService.feed_book_to_elf(
            elf_id=request.elf_id,
            book_id=request.book_id
        )
        return FeedBookResponse(**result)
    except ValueError as e:
        logger.error(f"喂养书籍参数错误: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"喂养书籍失败: {e}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.delete("/{book_id}/elf/{elf_id}")
async def remove_book_from_elf(book_id: str, elf_id: str):
    """
    删除精灵的书籍阅读记录
    """
    try:
        result = await BookService.remove_book_from_elf(
            elf_id=elf_id,
            book_id=book_id
        )
        if not result["success"]:
            raise HTTPException(status_code=404, detail=result["message"])
        return result
    except ValueError as e:
        logger.error(f"删除阅读记录参数错误: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除阅读记录失败: {e}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.get("/elf/{elf_id}", response_model=GetElfBooksResponse)
async def get_elf_books(elf_id: str):
    """
    获取精灵已阅读的所有书籍
    """
    try:
        books = await BookService.get_elf_books(elf_id)
        return GetElfBooksResponse(
            elf_id=elf_id,
            books=books,
            total_books=len(books)
        )
    except Exception as e:
        logger.error(f"获取精灵书籍列表失败: {e}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@router.get("/", response_model=List[Book])
async def get_all_books(
    min_age: Optional[int] = Query(None, ge=0, le=100),
    max_age: Optional[int] = Query(None, ge=0, le=100),
    book_type: Optional[str] = Query(None),
    region: Optional[str] = Query(None)
):
    """
    获取所有可用书籍（支持筛选）
    - min_age: 最小年龄
    - max_age: 最大年龄
    - book_type: 书籍类型
    - region: 地区（国内/海外）
    """
    try:
        books = await BookService.get_all_books(
            min_age=min_age,
            max_age=max_age,
            book_type=book_type,
            region=region
        )
        return books
    except Exception as e:
        logger.error(f"获取书籍列表失败: {e}")
        raise HTTPException(status_code=500, detail="服务器内部错误")